package gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import dbConnection.Database;

/**
 * Creates the gui for the Search Page for the
 * User view. This includes the necessary front end, 
 * and back end code.
 * 
 * @author Herndon, Prentice, Arslan
 *
 */
@SuppressWarnings("serial")
public class UserSearch extends JPanel {

	/** The Database object for the class. */
	public Database DB;

	/** The Id of the User */
	public int userID;

	/** The reference to the Main window */
	public MainScreen app;
	
	private JButton finesButton;

	/**
	 * Initializes the Gui + Backend code for the UserSearch  
	 * panel object.
	 * 
	 * @param DB A database object
	 * @param userID The id of the user
	 * @param app The main window
	 */
	public UserSearch(Database DB, int userID, final MainScreen app) {
		this.app = app;
		this.DB = DB;
		this.userID = userID;

		setLayout(new BorderLayout());

		final JPanel fieldSearch = new JPanel();
		final JPanel resultsPanel = new JPanel();
		final JPanel buttons = new JPanel();
		resultsPanel.setLayout(new BoxLayout(resultsPanel, BoxLayout.Y_AXIS));

		final JTextField itemID = new JTextField();
		final JTextField title = new JTextField();
		final JTextField author = new JTextField();
		final JTextField isbn = new JTextField();
		final JTextField type = new JTextField();

		final JLabel itemIDLabel = new JLabel("itemID");
		final JLabel titleLabel = new JLabel("Title");
		final JLabel authorLabel = new JLabel("Author");
		final JLabel isbnLabel = new JLabel("ISBN");
		final JLabel typeLabel = new JLabel("Type");

		final JButton search = new JButton("Search");

		fieldSearch.setLayout(new GridLayout(2,0));

		fieldSearch.add(itemID);
		fieldSearch.add(title);
		fieldSearch.add(author);
		fieldSearch.add(isbn);
		fieldSearch.add(type);
		fieldSearch.add(search);

		fieldSearch.add(itemIDLabel);
		fieldSearch.add(titleLabel);
		fieldSearch.add(authorLabel);
		fieldSearch.add(isbnLabel);
		fieldSearch.add(typeLabel);
		
		EnterListener searchListener = new EnterListener(search);
		itemID.addActionListener(searchListener);
		title.addActionListener(searchListener);
		author.addActionListener(searchListener);
		isbn.addActionListener(searchListener);
		type.addActionListener(searchListener);

		search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) { 
				resultsPanel.removeAll();  //This may cause problems
				if(UserSearch.this.DB.con != null) {
					Statement statement = null;
					ResultSet resultSet = null;
					try {
						statement = UserSearch.this.DB.con.createStatement();
						resultSet = statement.executeQuery("SELECT DISTINCT inventory.InventoryId,inventory.ItemId,item.Title,item.Author," +
								"item.ISBN,item.Type FROM inventory NATURAL JOIN item;");

						String[] keywords = {itemID.getText(), title.getText(), author.getText(),
								isbn.getText(), type.getText()};
						//if resultset is received and is not empty,
						// iterate over resultset to get values
						boolean cont = true;
						String keyword;
						String result;
						while (resultSet.next()) {	

							if (!keywords[0].equals("") && !resultSet.getString(2).equals((keywords[0]))) {
								continue;
							}	

							for (int i = 1; i < 5; i++) {
								keyword = keywords[i].toLowerCase();
								result = resultSet.getString(i+2).toLowerCase();

								if (keyword.equals("") || result.contains(keyword) ||
										result.equals(keyword)) {
									continue;
								} else {
									cont = false;
									break;
								}	
							} 
							if (cont) {
								resultsPanel.add(new UserSearchResult(UserSearch.this.userID, 
										Integer.parseInt(resultSet.getString(2)), UserSearch.this.DB));	
							}

							cont = true;
						}
					} catch (SQLException eee) {
						// 
					}
				}

				resultsPanel.revalidate();
				resultsPanel.repaint();
			}
		});

		buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));

		this.finesButton = new JButton("Pay Fines: " + getFines()); 
		JButton viewItems = new JButton("View My Items");
		JButton logout = new JButton("Logout");

		this.finesButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//set user fines to 0 in database
				if(UserSearch.this.DB.con != null) {
					try {
						Statement statement = UserSearch.this.DB.con.createStatement();
						statement.executeUpdate("UPDATE user SET Fines=0 WHERE " +
								"UserId=" + UserSearch.this.userID + ";");
						// reset fine tab
						UserSearch.this.finesButton.setText("Pay Fines: " + getFines());
					} catch (SQLException eee) {
						// do nothing
					}
				}
			}
		});

		viewItems.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resultsPanel.removeAll();
				// search for items checked out by this user, put them into resultsPanel
				if(UserSearch.this.DB.con != null) {
					try {
						Statement statement = UserSearch.this.DB.con.createStatement();
						ResultSet resultSet = statement.executeQuery("SELECT DISTINCT inventory.ItemId" +
								" FROM inventory " +
								"WHERE inventory.CheckoutStatus=\"Checked Out\" AND " +
								"inventory.UserId=" + UserSearch.this.userID + ";");

						//if resultset is received and is not empty,
						// iterate over resultset to get values
						while (resultSet.next()) {	
								resultsPanel.add(new UserSearchResult(UserSearch.this.userID,
										Integer.parseInt(resultSet.getString(1)), UserSearch.this.DB));	
						}
					} catch (SQLException eee) {
						// 
					}
				}
								
				resultsPanel.revalidate();
				resultsPanel.repaint();
			}
		});

		logout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				app.remove(app.uSearch);
				app.showLogin();
			}
		});

		buttons.add(this.finesButton);
		buttons.add(viewItems);
		buttons.add(logout);

		add(fieldSearch, BorderLayout.NORTH);
		add(resultsPanel,BorderLayout.CENTER);
		add(buttons,BorderLayout.SOUTH);

	}

	/**
	 * Queries the database to determine the fines of the user.
	 * 
	 * @return The fines the student owes.
	 */
	public double getFines() {
		double fines = 0.00;
		if(this.DB.con != null) {
			try {
				Statement statement = this.DB.con.createStatement();
				ResultSet resultSet = statement.executeQuery("SELECT Fines FROM user WHERE " +
						"UserId=" + this.userID + ";");

				if (resultSet != null && resultSet.next()) {							
					fines = Double.parseDouble(resultSet.getString(1));
				}
			} catch (SQLException eee) {
				//
			}
		}
		return fines;
	}  
}
